<template>
    <div>
        <div style="width: 100%;height: 10vh;">
            <div style="height: 30px;width: 100%;">
                <div style="display: flex;justify-content:space-between;">
                    <Row type="flex" justify="start" class="code-row-bg" style="float: left;padding-right: 5px; height: 40px;line-height: 60px;">
                        <div style="float:left; margin-left:10px; line-height: 40px;">
                            <Button size="small" icon="ios-cloud-upload" @click="value1 = true">上传</Button>
                            <Drawer title="Basic Drawer" :closable="false" v-model="value1">
                                <Upload multiple type="drag" :action="this.url" :data="{'parent_dir':'/'}">
                                    <div style="padding: 20px 0">
                                        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                        <p>Click or drag files here to upload</p>
                                    </div>
                                </Upload>
                            </Drawer>
                            <Button size="small" icon="ios-add-circle" @click="NewFolder = true">新建</Button>
                            <Modal title="新建文件夹" v-model="NewFolder" @on-ok="YesFolder" @on-cancel="Nofolder">
                                <Input v-model="FolderValue" placeholder="请输入新建文件夹的名称……" style="width: 100%;" />
                            </Modal>
                        </div>
                        <div style="margin-left:5px; line-height: 40px;">
                            <ButtonGroup>
                                <Button size="small" v-show="button" icon="md-trash" @click="Deletes">删除</Button>
                                <Button size="small" v-show="button" icon="md-cloud-download">下载</Button>
                                <Button size="small" v-show="button" icon="ios-copy">复制到</Button>
                                <Button size="small" v-show="button" icon="ios-albums">移动到</Button>
                            </ButtonGroup>
                        </div>
                    </Row>

                    <div style="display: flex;align-items: center;">
                        <div style="height: 40px;">
                            <i-switch size="small" v-model="switch1" @on-change="change" style="margin-top: 12px;float: right;margin-right: 10px;" />
                            <Input v-model="SearchValue" suffix="ios-search" size="small" placeholder="搜索" style="margin-top: 7px; width: auto; float: right; margin-right: 10px;"
                             @on-change="sousuo" />
                        </div>
                    </div>
                </div>
            </div>
            <div style="width: 100%;height: 30px;background: #000099;">
                <div style="height: 50px; background-color: #FFFFFF;">
                    <Row type="flex" justify="start" class="code-row-bg" style="float: left; ">
                        <div style="height: 50px; line-height: 50px; margin-left: 10px;">
                            <a style="color: #3f3f3f;" @click="Back">
                                <Icon type="ios-arrow-back" size="20" />
                            </a>
                            <!-- 返回上一层 -->
                            <a style="margin-left: 5px;" @click="Refresh">
                                <Icon type="md-refresh" color="#3f3f3f" size="20" />
                            </a>

                            <Divider type="vertical" size="default" />
                        </div>
                        <Breadcrumb>
                            <a style="height: 50px; line-height: 50px;color: #3f3f3f;" @click="aaaaa(index)" v-for="(item,index) in path">
                                <BreadcrumbItem>
                                    <Icon type="ios-home-outline"></Icon>
                                    {{item}}
                                </BreadcrumbItem>
                            </a>
                        </Breadcrumb>
                    </Row>
                </div>
            </div>
        </div>
        <div></div>
        <div style="width: 100%;height: 76vh;overflow:auto;">
            <Table :columns="columns1" :data="list" v-if="!switch1" @on-selection-change="select" @on-row-dblclick="dbClick"
             show-context-menu @on-contextmenu="handleContextMenu">
                <template slot="contextMenu">
                    <DropdownItem @click.native="handleContextMenuDownload">下载</DropdownItem>
                    <DropdownItem @click.native="NewFile = true">重命名</DropdownItem>
                    <Modal title="重命名" v-model="NewFile" @on-ok="YesFile" @on-cancel="NoFile">
                        <Input v-model="FileValue" placeholder="请输入重命名的名称……" style="width: 100%;" />
                    </Modal>
                    <DropdownItem @click.native="handleContextMenuCopy" v-if="Copy == true">复制</DropdownItem>
                    <DropdownItem @click.native="handleContextMenuCopy" v-else>粘贴</DropdownItem>
                    <DropdownItem @click.native="move">移动</DropdownItem>
                    <DropdownItem @click.native="handleContextMenuDelete" style="color: #ed4014">删除</DropdownItem>
                </template>
            </Table>
        </div>
        <!-- <ul v-for="item in list">
            <h1>{{item.server_filename}}</h1>
    </ul>-->
    </div>
</template>

<script>
    import axios from "axios";
    import qs from "qs";
    export default {
        data() {
            return {
                url:'',
                list: [], //文件列表
                button: false, //多选显示按钮
                value: "", //新建文件夹的value
                switch1: false, //切换缩略图
                SearchValue: "", //搜索文件value
                Selection: [], //多选按钮事件
                NewFolder: false, //新建var id = windows文件夹弹窗
                FolderValue: "", //新建文件夹value
                path: [], //面包屑路径
                value1: false,
                NewFile: false, //点击重命名界面
                ContextMenu: [], //右击选择文件
                Copy: true,
                CopyFile:[],// 复制文件信息
                CopyPath:"",// 复制文件路径信息
                FileValue:"",//重命名文件夹Value
                columns1: [{
                        type: "selection",
                        width: 60,
                        align: "center"
                    },
                    {
                        title: "文件名",
                        key: "name"
                    },
                    {
                        title: "最后修改时间",
                        key: "mtime",
                        width: 300,
                        align: "center"
                    },
                    {
                        title: "文件大小",
                        key: "size",
                        width: 150,
                        align: "center"
                    }
                ]
            };
        },
        mounted() {
            //获取文件列表
            this.Refresh();

            var id = window.sessionStorage.getItem('Seafile_id')
            var Token = window.localStorage.getItem('Token')
            //获取上传链接
            axios({
                url: 'https://cloud.seafile.com/api2/repos/' + id + '/upload-link/?p=/',
                method: 'get',
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                    'Authorization': 'Token ' + Token,
                    'Accept': 'application/json',
                    'indent': '4'
                }
            }).then((res) => {
                console.log(res)
                this.url = res.data
                console.log(this.url)
            })


        },
        methods: {
            aaaaa(row, index) {
                // 获取点击的名字
                var name = this.path[row];
                // 将数组转换字符串
                var Clickpath = this.path.join("/");
                // 截取到点击的路径
                var path = Clickpath.substring(
                    0,
                    Clickpath.lastIndexOf(name) + name.length
                );
                // 将路径转换成数组
                this.path = path.split("/");
                this.Refresh();
            },
            //刷新文件列表
            Refresh() {

                var _this = this;
                var id = window.sessionStorage.getItem("Seafile_id");
                var Token = window.localStorage.getItem("Token");
                var path = this.path.join("/");
                axios
                    .get(
                        "https://cloud.seafile.com/api2/repos/" + id + "/dir/?p=/" + path, {
                            headers: {
                                // 请求头
                                Accept: "application/json; indent=4",
                                Authorization: "Token " + Token
                            }
                        }
                    )
                    .then(function(respanse) {
                        _this.list = respanse.data;

                        console.log(respanse.data);
                        _this.list = respanse.data;
                        if (_this.list.length != 0) {
                            for (var i = 0; i < _this.list.length; i++) {
                                //定义空字符串size
                                var size = "";
                                //获取数组内的size并赋值变量
                                var fileSize = _this.list[i].size;
                                //判断文件大小
                                if (fileSize < 1024) {
                                    size = fileSize + "B";
                                } else if (fileSize < 1048576) {
                                    size = (fileSize / 1024).toFixed(1) + "K";
                                } else if (fileSize < 1073741824) {
                                    size = (fileSize / 1048576).toFixed(1) + "M";
                                } else {
                                    size = (fileSize / 1073741824).toFixed(1) + "G";
                                }
                                // 将数据重新放入到obj数组里面
                                var obj = _this.list[i]; //或者 var obj=new Object();
                                var key = "size";
                                obj[key] = size;
                                console.info(obj);

                                // 获取文件时间戳
                                var time = _this.list[i].mtime;
                                // 时间戳换算
                                var timestamp4 = new Date(time * 1000);
                                //拼接日期
                                var FileTime =
                                    timestamp4.toLocaleDateString().replace(/\//g, "-") +
                                    " " +
                                    timestamp4.toTimeString().substr(0, 8);
                                // 更改数组
                                var key = "mtime";
                                obj[key] = FileTime;
                                console.info(obj);
                            }
                        }
                    });
            },
            //批量操作
            select(Selection) {
                //对选中的数据 显示按钮，执行操作
                //将选中的数据，存储到数组里面，以便使用
                this.Selection = Selection;

                if (Selection.length != 0) {
                    this.button = true;
                } else {
                    this.button = false;
                }

                console.log(Selection);
            },
            //缩略图切换
            change(status) {
                this.$Message.info("开关状态：" + status);
            },
            //搜索文件
            sousuo() {
                var Token = window.localStorage.getItem("Token");
                if (this.SearchValue != "") {
                    const value = this.SearchValue;
                    axios({
                        url: "https://cloud.seafile.com/api2/search/?q=" + value,
                        method: "get",
                        headers: {
                            Authorization: "Token " + Token,
                            Accept: " application/json; indent=4"
                        }
                    }).then(res => {
                        console.log(res.data.results);
                        this.list = res.data.results;
                    });
                } else {
                    this.Refresh();
                }
            },
            //tab表格双击事件
            dbClick(row) {
                if (row.type == "dir") {
                    //更改面包屑
                    console.log(row.name); //文件夹名称
                    this.path.splice(this.path.length, 0, row.name);
                    //进入子目录
                    this.Refresh();
                } else {
                    
                }
            },
            //确定新建文件夹
            YesFolder() {
                //获取输入的value
                var value = this.FolderValue;
                // 获取Token
                var Token = window.localStorage.getItem("Token");
                // 将数组转换成字符串
                var path = "/" + this.path.join("/");
                // 获取资料库id
                var id = window.sessionStorage.getItem("Seafile_id");
                axios({
                    url: "https://cloud.seafile.com/api2/repos/" +
                        id +
                        "/dir/?p=" +
                        path +
                        "/" +
                        value,
                    method: "post",
                    data: qs.stringify({
                        operation: "mkdir"
                    }),
                    headers: {
                        Authorization: "Token " + Token,
                        Accept: "application/json; charset=utf-8; indent=4"
                    }
                }).then(res => {
                    this.$Message.success("新建文件夹：" + value);
                    this.Refresh();
                });
            },
            //取消新建文件夹
            Nofolder() {
                this.$Message.warning("已取消新建文件夹！");
            },
            //批量删除
            Deletes() {
                var Selection = this.Selection;
                if (Selection.length != 0) {
                    this.$Modal.confirm({
                        title: "温馨提示",
                        content: "<p>是否需要删除该文件？</p>",
                        onOk: () => {
                            for (var i = 0; i < Selection.length; i++) {
                                var Token = window.localStorage.getItem("Token");
                                var id = window.sessionStorage.getItem("Seafile_id");
                                var path = this.path.join("/");

                                axios
                                    .delete(
                                        "https://cloud.seafile.com/api2/repos/" +
                                        id +
                                        "/file/?p=/" +
                                        path +
                                        "/" +
                                        Selection[i].name, {
                                            headers: {
                                                // 请求头
                                                Accept: "application/json; indent=4",
                                                Authorization: "Token " + Token
                                            }
                                        }
                                    )
                                    .then(res => {
                                        console.log(res);
                                        this.Refresh();
                                        this.button = false;
                                    });
                            }
                        },
                        onCancel: () => {
                            this.$Message.info("已经取消删除操作");
                        }
                    });
                } else {
                    this.$Message.error("请先勾选文件，再执行删除！");
                }
            },
            // 返回上一层
            Back() {
                //判断是否为根目录
                if (this.path.length == 0) {
                    this.$router.push("/Seafile_Home");
                }
                //当前目录-1
                this.path.splice(-1, 1);
                //刷新目录
                this.Refresh();
            },
            // 右击事件
            handleContextMenu(row) {
                console.log(row);
                this.ContextMenu = row;
            },
            // 单文件下载
            handleContextMenuDownload() {
                var Token = window.localStorage.getItem("Token");
                var id = window.sessionStorage.getItem("Seafile_id");
                var name = this.ContextMenu.name;
                var path = this.path.join("/");
                axios({
                    url: "https://cloud.seafile.com/api2/repos/" +
                        id +
                        "/file/?p=/" +
                        path +
                        "/" +
                        name,
                    method: "get",
                    headers: {
                        // 请求头
                        Accept: "application/json; indent=4",
                        Authorization: "Token " + Token
                    }
                }).then(res => {
                    console.log(res.data);

                    var url = res.data
                    axios({
                        url: "http://127.0.0.1:6800/jsonrpc",
                        method: "post",
                        crossDomain: true,
                        processData: false,
                        data: JSON.stringify({
                            id: "",
                            jsonrpc: "2.0",
                            method: "aria2.addUri",
                            params: [
                                "token:kumao",
                                [url],
                                {
                                    "download-result": "full",
                                    header: "User-Agent:pan.baidu.com",
                                    out: name
                                }
                            ]
                        }),
                        headers: {
                            contentType: "application/json"
                        }
                    }).then(res => {});
                    this.$Message.success("已将选中文件，添加到下载队列！");



                });
            },
            handleContextMenuDelete() {

                this.$Modal.confirm({
                    title: "删除文件",
                    content: "是否删除：" + this.ContextMenu.name + "？",
                    onOk: () => {
                        var Token = window.localStorage.getItem("Token");
                        var id = window.sessionStorage.getItem("Seafile_id");
                        var path = this.path.join("/");
                        var name = this.ContextMenu.name;

                        axios
                            .delete(
                                "https://cloud.seafile.com/api2/repos/" +
                                id +
                                "/file/?p=/" +
                                path +
                                "/" +
                                name, {
                                    headers: {
                                        // 请求头
                                        Accept: "application/json; indent=4",
                                        Authorization: "Token " + Token
                                    }
                                }
                            )
                            .then(res => {
                                console.log(res);
                                this.Refresh();
                            });
                    },
                    onCancel: () => {
                        this.$Message.info("已经取消删除操作");
                    }
                });
            },
//    复制单文件
            handleContextMenuCopy() {
                // 判断当前状态是复制还是粘贴
                if (this.Copy == true) {
                    this.CopyFile =  this.ContextMenu;
                    this.CopyPath =  this.path.join("/");
                    this.$Message.success(
                        "复制文件：" + this.ContextMenu.name + "成功！"
                    );
                    this.Copy = !this.Copy;
                } else {
                    var Token = window.localStorage.getItem("Token");
                    var id = window.sessionStorage.getItem("Seafile_id");
                    var path = this.path.join("/");
                    var name = this.CopyFile.name;
                    console.log(this.CopyFile)
                    axios({
                        url: 'https://cloud.seafile.com/api/v2.1/repos/sync-batch-copy-item/',
                        method: 'post',
                        data: {
                            dst_parent_dir: '/'+path,
                            dst_repo_id: id,
                            src_dirents: [name],
                            src_parent_dir: '/'+ this.CopyPath,
                            src_repo_id: id,
                        },
                        headers: {
                            // 请求头
                            Accept: "application/json; indent=4",
                            Authorization: "Token " + Token
                        }
                    }).then((res)=>{
                        // console.log(res)
                        this.Refresh()
                    })
                    this.Copy = !this.Copy;
                }
            },
            // 确定重命名
            YesFile() {

                var value = this.FileValue;
                var Token = window.localStorage.getItem("Token");
                var path = this.path.join("/");
                var id = window.sessionStorage.getItem('Seafile_id')
                var name = this.ContextMenu.name
                this.$Message.success("重命名：" + value);
                axios({
                    url: 'https://cloud.seafile.com/api2/repos/' + id + '/file/?p=/' + path + name,
                    method: 'post',
                    headers: {
                        // 请求头
                        Accept: "application/json; indent=4",
                        Authorization: "Token " + Token
                    },
                    data: qs.stringify({
                        operation: 'rename',
                        newname: value
                    })
                }).then(res => {

                    var _this = this;
                    setTimeout(function() {

                        _this.Refresh();
                    }, 500);
                });
                var _this = this;
                setTimeout(function() {

                    _this.Refresh();
                }, 1000);
            },
            // 取消重命名
            NoFile() {
                this.$Message.warning("已取消重命名！");
            },
            // 移动文件
            move() {

                var Token = window.localStorage.getItem("Token");
                var id = window.sessionStorage.getItem("Seafile_id");
                var path = this.path.join("/");
                var name = this.ContextMenu.name;
                var FileId = this.ContextMenu.id
                axios({
                    url: 'https://cloud.seafile.com/api2/repos/' + id + '/file/?p=/' + path + name,
                    method: 'post',
                    data: {
                        'dst_repo': id,
                        'dst_dir': '/文件夹1',
                        'file_names': name
                    },
                    headers: {
                        // 请求头
                        Accept: "application/json; indent=4",
                        Authorization: "Token " + Token
                    }
                }).then((res) => {
                    console.log(res)
                })
            }
        }
    };
</script>
